package com.logicvoid.rosiesettingsz;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private OnClickListener myClickListener;
	
	final int APP_SELECT_LEFT = 0;
	final int APP_SELECT_RIGHT = 1;

	final String LEFT_BUTTON_DEFAULT_PACKAGE = "com.android.htcdialer";
	final String RIGHT_BUTTON_DEFAULT_PACKAGE = "com.android.browser";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Lets make sure this isn't a kanged Rosie Settings implementation
		if (KangDetection.isKanged()) {
			Toast.makeText(
					getBaseContext(),
					"You are running a KANGED version of Rosie Settings.",
					Toast.LENGTH_LONG).show();

			// Launch Kanged URL for them :)

			try {

				String url = "http://www.urbandictionary.com/define.php?term=kang";
				Intent i = new Intent(Intent.ACTION_VIEW);
				Uri u = Uri.parse(url);
				i.setData(u);
				startActivity(i);

			} catch (Exception e) {

				Toast.makeText(getBaseContext(), "Error: " + e.toString(),
						Toast.LENGTH_LONG).show();
			}
			// End Launch URL
			this.finish();
			return;
		}

		/*
		 * // Left button handler Button leftButton = (Button)
		 * findViewById(R.id.btnLeft); leftButton.setOnClickListener(new
		 * View.OnClickListener() { public void onClick(View view) {
		 * 
		 * Intent myIntent = new Intent(); myIntent.setClass(MainActivity.this,
		 * AppChooserActivity.class); startActivityForResult(myIntent,
		 * APP_SELECT_LEFT); }
		 * 
		 * });
		 */

		// Right Button Handler
		myClickListener = new View.OnClickListener() {
		  public void onClick(View view) {
		    Intent myIntent = new Intent();
			myIntent.setClass(MainActivity.this, AppChooserActivity.class);
			startActivityForResult(myIntent, APP_SELECT_RIGHT);
		  }			
		};
		//((Button)findViewById(R.id.btnRight)).setOnClickListener(myClickListener);
		((Button)findViewById(R.id.mainActivity_SelectButton)).setOnClickListener(myClickListener);
		
		/*
		// Right Button Handler
		Button rightButtonDelete = (Button) findViewById(R.id.btnRightDelete);
		rightButtonDelete.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				Intent myIntent = new Intent();
				myIntent.setClass(MainActivity.this, AppDeleteActivity.class);
				startActivityForResult(myIntent, APP_DELETE_RIGHT);
			}
			

		});
		*/
		

		// Refresh
		refreshPackageSelections();

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case APP_SELECT_LEFT:
			if (resultCode == RESULT_OK) {
				String name = data.getStringExtra("SelectedApp");
				// Toast.makeText(this, "You have chosen the App: " + " " +
				// name, Toast.LENGTH_LONG).show();

				// commit this preference
				Preferences.setStringPreferenceValue("leftButtonPackageName",
						name, getApplicationContext());

				// Refresh
				refreshPackageSelections();

			}
			break;

		case APP_SELECT_RIGHT:
			if (resultCode == RESULT_OK) {
				String name = data.getStringExtra("SelectedApp");
				// Toast.makeText(this, "You have chosen the App: " + " " +
				// name, Toast.LENGTH_LONG).show();

				// commit this preference
				Preferences.setStringPreferenceValue("rightButtonPackageName",
						name, getApplicationContext());

				// Refresh
				refreshPackageSelections();
			}
			break;

		default:
			break;
		}
	}

	protected void refreshPackageSelections() {

		// Retrive default packages if nothing assigned to buttons
		//String leftButtonDefaultPackage = getText(
		//		R.string.left_button_default_package).toString();
		String rightButtonDefaultPackage = getText(
				R.string.right_button_default_package).toString();

		// Retrieve package name from preferences
		//String leftButtonpackageName = Preferences.getStringPreferenceValue(
		//		"leftButtonPackageName", leftButtonDefaultPackage,
		//		getApplicationContext());
		
		//Need to know if no preference currently set
		String prefSet = Preferences.getStringPreferenceValue("rightButtonPackageName","",getApplicationContext());
		//Toast.makeText(this, prefSet, Toast.LENGTH_LONG).show();
		
		String rightButtonpackageName = Preferences.getStringPreferenceValue(
				"rightButtonPackageName", rightButtonDefaultPackage,
				getApplicationContext());


		try {
			// Left Button Display App Info Handling
			PackageManager packageManagerLeftButton = getPackageManager();
			// PackageInfo piLeftButton = packageManagerLeftButton.getPackageInfo(leftButtonpackageName, 0);

			// Display AppName
			/*
			 * TextView tvBtnLeftAppName = (TextView)
			 * findViewById(R.id.tvBtnLeftAppName);
			 * tvBtnLeftAppName.setText(piLeftButton
			 * .applicationInfo.loadLabel(packageManagerLeftButton));
			 */

			// Display (com.package.name)
			// TextView tvBtnLeftPackageName = (TextView)
			// findViewById(R.id.tvBtnLeftPackageName);
			// tvBtnLeftPackageName.setText("(" + piLeftButton.packageName
			// +")");

			// Display icon
			/*
			 * ImageView ivBtnLeft = (ImageView)
			 * findViewById(R.id.app_icon_btn_left);
			 * ivBtnLeft.setImageDrawable(piLeftButton
			 * .applicationInfo.loadIcon(packageManagerLeftButton));
			 */

			// Right Button Display App Info Handling
			PackageManager packageManagerRightButton = getPackageManager();
			PackageInfo piRightButton = packageManagerLeftButton
					.getPackageInfo(rightButtonpackageName, 0);

			// Display AppName (com.package.name)
			TextView tvBtnRightAppName = (TextView) findViewById(R.id.tvBtnRightAppName);
			tvBtnRightAppName.setText(piRightButton.applicationInfo
					.loadLabel(packageManagerRightButton));

			// Display (com.package.name)
			// TextView tvBtnRightPackageName = (TextView)
			// findViewById(R.id.tvBtnRightPackageName);
			// tvBtnRightPackageName.setText("(" + piRightButton.packageName
			// +")");

			// Display icon
			ImageView ivBtnRight = (ImageView) findViewById(R.id.app_icon_btn_right);
			ivBtnRight.setImageDrawable(piRightButton.applicationInfo
					.loadIcon(packageManagerRightButton));
			
			//check to see if user has selected a default application, if so, show 'select','delete', else, 'select' only.
			if(!prefSet.equals("")) {
		      findViewById(R.id.mainActivity_RowLL).setVisibility(View.VISIBLE);
		      findViewById(R.id.mainActivity_SelectButton).setVisibility(View.GONE);
			} else {
			  findViewById(R.id.mainActivity_RowLL).setVisibility(View.GONE);
			  findViewById(R.id.mainActivity_SelectButton).setVisibility(View.VISIBLE);
			}
		}

		catch (Exception e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
		}

	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);

		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		boolean result = true;

		switch (item.getItemId()) {
		case R.id.menu_about: {
			displayAboutDialog();

			break;
		}
		}

		return result;

	}

	private void displayAboutDialog() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);

		String version = com.logicvoid.rosiesettingsz.Application
				.getVersionName(getApplicationContext(), getClass());

		builder.setTitle(getString(R.string.app_name));
		builder.setMessage("Version " + version + "\r\n\r\n"
				+ getString(R.string.app_desc));

		builder.show();
	}

	//Added by JsChiSurf, option to delete setting to return to stock Personalize screen
	public void btn_preferenceDelete(View v) {

		final String TAG = "Preferences";
		final String PREFS_NAME = "preferences"; // used as main key for SharedPreferences
		try {

				// Save user preferences. We need an Editor object to
				// make changes. All objects are from android.context.Context

				SharedPreferences settings = getSharedPreferences(
						PREFS_NAME, 2); // 2 = MODE_WORLD_WRITEABLE1
				Editor e = settings.edit();
				e.clear();
				e.commit();
				String selectedFilePath = "/data/data/com.logicvoid.rosiesettingsz/shared_prefs/preferences.xml";
				File file = new File(selectedFilePath);
				file.delete();				

			} catch (Exception ex) {
				Log.e(TAG, "Exception in btn_preferenceDelete", ex);
			}
    
			// Remove the Delete Button, show the main Select button
			findViewById(R.id.mainActivity_RowLL).setVisibility(View.GONE);
			findViewById(R.id.mainActivity_SelectButton).setVisibility(View.VISIBLE);
			this.refreshPackageSelections();
			
			Toast.makeText(this, "Preference has been deleted.", Toast.LENGTH_LONG).show();
			
			return;
		}
	
}
